import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import type { ActionReducerMapBuilder, AsyncThunk, PayloadAction, Slice } from '@reduxjs/toolkit'
import { getUser, GetUserParams } from './searchUserAPI'

interface InitialState  {
  params: GetUserParams,
  table: {
    status: 'init' | 'success' | 'error' | 'loading',
    data?: Res
  },
  modal: {
    open: boolean
  }
}

const initialState:InitialState = {
  params: {
    query_user_id: ''
  },
  table: {
    status: 'init'
  },
  modal:{
    open:false
  }
}

type Res = {
  data: Record<string, string| number>
}
type AsyncRes = {
  res: Res,
  params: GetUserParams
}
export const getUserAsync:AsyncThunk<AsyncRes,GetUserParams,{}> = createAsyncThunk<AsyncRes,GetUserParams,{}>('searchUser/getUserAsync', async params => {
  const res:Res = await getUser(params)
  return {
    res,params
  }
})
const tableStatus = (builder: ActionReducerMapBuilder<InitialState>) => {
  builder.addCase(getUserAsync.pending, state => {
    state.table.status = 'loading'
  }).addCase(getUserAsync.fulfilled, (state, action) => {
    state.table.status = 'success'
    state.table.data = action.payload.res
  }).addCase(getUserAsync.rejected, state => {
    state.table.status = 'error'
  })
}

type Reducers = {
  changeParams: (state:InitialState, action:PayloadAction<Partial<InitialState['params']>>) => void
  changeModal: (state:InitialState, action:PayloadAction<Partial<InitialState['modal']>>) => void
}
type Selectors = {}
const searchUserSlice:Slice<InitialState, Reducers, 'searchUser', 'searchUser', Selectors> = createSlice<InitialState, Reducers, 'searchUser', Selectors, 'searchUser'>({
  name: 'searchUser',
  initialState,
  reducers: {
    changeParams(state, action){
      state.params = {
        ...state.params,
        ...action.payload
      }
    },
    changeModal(state,action){
      state.modal = {
        ...state.modal,
        ...action.payload
      }
    }
  },
  extraReducers(builder){
    tableStatus(builder)
  }
})

export const { changeParams, changeModal } = searchUserSlice.actions

export default searchUserSlice.reducer

